package com.hbsoft.wechat.service;

import com.hb.bean.CallResult;
import com.hb.util.StringUtil;
import com.hbsoft.util.ImageUtil;
import com.hbsoft.util.WechatUtil;
import com.hbsoft.wechat.bean.BusInfo;
import com.hbsoft.wechat.bean.Swan;
import com.hbsoft.wechat.dao.service.BusInfoDaoService;
import com.hbsoft.wechat.dao.service.SwanDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WechatAppletService {

    @Autowired
    private SwanDaoService swanDaoService;
    @Autowired
    WechatUtil wechatUtil;
    @Autowired
    BusInfoDaoService busInfoDaoService;


    public CallResult<String> addSwanAndQrCode(String name) throws Exception {
        CallResult<String> result = new CallResult<String>();
        if (StringUtil.isEmpty(name)) {
            result.setCode(400);
            result.setMsg("添加失败");
            return result;
        }

        Swan param = new Swan();
        param.setName(name);
        Swan sw = swanDaoService.getByField(param);
        if (sw == null) {
            Swan swan = new Swan();
            String qrName = "gg_" + name;
            String qrCode = "";
            while (true) {
                String s = StringUtil.randomNumId(6);
                String code = s.substring(s.length() - 6);
                code = code.replace("4", "0");
                Swan swanParam = new Swan();
                swanParam.setQrCode(code);
                List<Swan> all = swanDaoService.getAll(swanParam);
                if (all.size() == 0) {
                    qrCode = code;
                    break;
                }
            }

            String qrCodeUrl = wechatUtil.getWxAappQrCode("gg_" + qrCode);
            swan.setQrCode(qrCode);
            swan.setOpenId("ow3dt5T9-obGy4v8zs-dR6oEZw8g");
            swan.setName(name);
            swan.setType("公交车");
            swan.setQrCodeUrl(qrCodeUrl);
            swan.setCreateDate(new Date());
            swan.setFlag("1");

            swanDaoService.add(swan);
            result.setCode(0);
            result.setMsg("添加成功");
            result.setData(qrCode);
        } else {
            result.setCode(400);
            result.setMsg("二维码已存在");
        }
        return result;
    }

    public String renameFile() throws Exception {

        List<BusInfo> list = busInfoDaoService.getAll(null);
        for (BusInfo b : list) {
            Swan param = new Swan();
            param.setName(b.getBusName());
            Swan swan = swanDaoService.getByField(param);
            if (swan != null) {
                String path = "D:\\qr\\img\\gg_" + swan.getQrCode() + ".jpg";
                String outPath = "D:\\qr\\img\\" + b.getBusType() + "\\" + b.getBusName() + ".jpg";
                ImageUtil.copy2(path, outPath);
            }
        }

        return null;
    }
}
